package com.oj.exception;

import com.oj.service.impl.I18nService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.oj.util.*;

import java.util.*;

@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler  {
    @ExceptionHandler(JsonOJException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handleJsonOJException(JsonOJException ex) {
        return Result.error(ex.getCodeMsg().locale());
    }

    @ExceptionHandler(OJException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleOJException(OJException ex) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", ex.getCodeMsg().locale().getMsg());
        mv.setViewName("error/error.html");
        return mv;
    }

    /**
     * 方法参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodValidationExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        List<Map> errMsg = new ArrayList<Map>();
        for (FieldError err: fieldErrors) {
            Map em = new HashMap();
            em.put(err.getField(), err.getDefaultMessage());
            errMsg.add(em);
        }

        return Result.error(0, errMsg);
    }
}
